package com.hidewnd.shiro.plugins;

import cn.hutool.core.util.StrUtil;
import com.mikuac.shiro.annotation.AnyMessageHandler;
import com.mikuac.shiro.annotation.GroupMessageHandler;
import com.mikuac.shiro.annotation.MessageHandlerFilter;
import com.mikuac.shiro.annotation.PrivateMessageHandler;
import com.mikuac.shiro.annotation.common.Shiro;
import com.mikuac.shiro.common.utils.MsgUtils;
import com.mikuac.shiro.core.Bot;
import com.mikuac.shiro.dto.event.message.AnyMessageEvent;
import com.mikuac.shiro.dto.event.message.GroupMessageEvent;
import com.mikuac.shiro.dto.event.message.PrivateMessageEvent;
import com.mikuac.shiro.enums.AtEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.regex.Matcher;


@Slf4j
@Shiro
@Component
public class ExamplePlugin {

    // 当机器人收到的私聊消息消息符合 cmd 值 "hi" 时，这个方法会被调用。
    @PrivateMessageHandler
    @MessageHandlerFilter(cmd = "hi")
    public void fun1(Bot bot, PrivateMessageEvent event, Matcher matcher) {
        // 构建消息
        String sendMsg = MsgUtils.builder().face(66).text("this is privateMessage callBack").build();
        // 发送私聊消息
        bot.sendPrivateMsg(event.getUserId(), sendMsg, false);
    }

    // 如果 at 参数设定为 AtEnum.NEED 则只有 at 了机器人的消息会被响应
    @GroupMessageHandler
    @MessageHandlerFilter(at = AtEnum.NEED)
    public void fun2(GroupMessageEvent event) {
        // 以注解方式调用可以根据自己的需要来为方法设定参数
        // 例如群组消息可以传递 GroupMessageEvent, Bot, Matcher 多余的参数会被设定为 null
        log.info("群组消息: {}", event.getMessage());
    }

    @GroupMessageHandler
    @MessageHandlerFilter(startWith = "测试")
    public void fun3(Bot bot, GroupMessageEvent event, Matcher matcher) {
        String message = event.getMessage();
        String group = matcher.group();
        String text = StrUtil.format("收到群组消息: {}，匹配到的内容: {}", message, group);
        bot.sendGroupMsg(event.getGroupId(), text, false);
    }

    // 同时监听群组及私聊消息 并根据消息类型（私聊，群聊）回复
    @AnyMessageHandler
    @MessageHandlerFilter(cmd = "hi")
    public void fun3(Bot bot, AnyMessageEvent event) {
        bot.sendMsg(event, "this is GroupMessage callBack", false);
    }

    @GroupMessageHandler
    @MessageHandlerFilter(cmd = "^匹配 (.*)?$")
    public void fun4(Bot bot, GroupMessageEvent event, Matcher matcher) {
        int index = 1;
        String message = matcher.group(0);
        String group = matcher.group(index);
        while (StrUtil.isNotEmpty(group)) {
            String text = StrUtil.format("收到群组消息: {}，匹配到的内容: {}", message , group);
            bot.sendGroupMsg(event.getGroupId(), text, false);
            group = matcher.groupCount() < index ? matcher.group(++index) : null;
        }

    }
}
